document.addEventListener("DOMContentLoaded", function() {
    const bookList = document.getElementById("hot-list");
    const pagination = document.getElementById("pagination");
    let currentPage = 1;
    const booksPerPage = 10;  
    let booksData = []; 
    fetchBooksData();
    function fetchBooksData() {
        fetch("/data/popular")
            .then(response => response.json())
            .then(data => {
                booksData = data;
                renderBooks(currentPage);
                generatePagination(booksData.length);
            })
            .catch(error => console.error("Error fetching books:", error));
    }
    function renderBooks(page) {
        const startIndex = (page - 1) * booksPerPage;
        const endIndex = startIndex + booksPerPage;
        bookList.innerHTML = ""; 
        for (let i = startIndex; i < endIndex && i < booksData.length; i++) {
            const book = booksData[i];
            const li = document.createElement("li");
            li.innerHTML = `
                <a href="${book.pdf}" download>
                    <span>${book.title} | ${book.author}</span>
                    <div>${book.description}</div>
                </a>
            `;
            bookList.appendChild(li);
        }
    }

    function generatePagination(totalBooks) {
        pagination.innerHTML = "";
        const totalPages = Math.ceil(totalBooks / booksPerPage);
        if (currentPage > 1) {
            const prevButton = document.createElement("li");
            prevButton.classList.add("page-item");
            prevButton.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage - 1})">Previous</a>`;
            pagination.appendChild(prevButton);
        }

        for (let i = 1; i <= totalPages; i++) {
            const pageItem = document.createElement("li");
            pageItem.classList.add("page-item");
          if (i === currentPage) {
            pageItem.classList.add("active");
          }
          pageItem.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
          pagination.appendChild(pageItem);
        }

        if (currentPage < totalPages) {
            const nextButton = document.createElement("li");
            nextButton.classList.add("page-item");
            nextButton.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage + 1})">Next</a>`;
            pagination.appendChild(nextButton);
        }
    }
    function changePage(newPage) {
        currentPage = newPage;
        renderBooks(currentPage);
    }
});
